<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="送检单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="purchase_inspect" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="送检人员" prop="inspectName">
          <el-input v-model="formData.inspectName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="送检日期" prop="inspectTime">
          <el-date-picker
            v-model="formData.inspectTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="采购订单号" class="clickChoose" prop="purchaseOrderCode">
          <el-input v-model="formData.purchaseOrderCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="choosePeople"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="formData.supplierName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <!-- 订单明细 -->
        <div />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="listDate"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :summary-method="getSummaries"
          :header-cell-class-name="headerCellClassName"
          show-summary
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="70" />
          <el-table-column label="物料编码" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="purchaseNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.purchaseNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="送检数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="inspectNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inspectNumber" placeholder="请输入" clearable type="number" />
            </template>
          </el-table-column>
          <el-table-column label="已检验数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="qualityNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.qualityNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已入库数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="alreadyStorageNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.alreadyStorageNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已退货数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="returnedNumber">
            <template slot-scope="scope">
              <span>{{ scope.row.returnedNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" style="width: 130px" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSave">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getInfoForInspect } from '@/api/purchaseManage/materialToCheck'
import purchaseOrder from './purchaseOrder'
import addOrderDetail from './addOrderDetail'
import moment from 'moment'
import Big from 'big.js' // big.js解决精度丢失问题
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        model: undefined,
        fileName: '',
        fileRealName: '',
        url: '',
        remark: undefined,
        purchaseOrderCode: undefined,
        supplierName: '',
        inspectTime: '',
        status: 1,
        detailList: []
      },
      foDate: {
        companyId: undefined,
        status: 1
      },
      orderId: '',
      tableHeight: '',
      userOptions: [],
      equipmentList: [],
      selectionsAll1: [],
      ids: [],
      roleOptions: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      tableDate: [],
      listDate: [],
      rules: {
        purchaseOrderCode: [
          { required: true, message: '采购订单号不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '送检单号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    listDate() {
      if (this.listDate.length > 7) {
        this.tableHeight = '390'
      } else {
        this.tableHeight = ''
      }
      console.log(this.listDate)
      this.$refs['table'].doLayout()
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table'].doLayout()
    })
  },
  created() {
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.formData.inspectName = this.$store.state.user.name
    this.formData.inspectBy = this.$store.state.user.userId
    this.formData.inspectTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'url', data[2])
    },
    headerCellClassName(data) {
      if (['inspectNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    // 合计行
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'purchaseNumber':
            sums[index] = data.map(item => item.purchaseNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.totalNumber = sums[index]
            break
        }
        switch (column.property) {
          case 'inspectNumber':
            sums[index] = data.map(item => item.inspectNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.inspectNumber = sums[index]
            break
        }
        switch (column.property) {
          case 'qualityNumber':
            sums[index] = data.map(item => item.qualityNumber).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.qualityNumber = sums[index]
            break
        }
      })
      return sums
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.orderId = res.data.purchaseOrderId
        this.formData = res.data
        this.listDate = res.data.detailList
        if (this.formData.purchaseOrderCode == '' || this.formData.purchaseOrderCode == null) {
          this.formData.purchaseOrderCode = undefined
        }
        this.formData.roleIdsArray = this.formData.roleIds.split(',')
      })
    },
    getOrderGetInfo() {
      getInfoForInspect(this.orderId).then(res => {
        this.listDate = res.data.detailList
        this.listDate.forEach(item => {
          item.purchaseOrderDetailId = item.id
          item.id = ''
          delete item.id
          item.remark = ''
        })
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.listDate.splice(this.listDate.indexOf(item), 1)
      })
    },
    add() {
      if (!this.formData.purchaseOrderCode) {
        this.$message.warning('请选择采购订单号')
        return
      }
      this.$layer.iframe({
        // // 弹框
        content: {
          content: addOrderDetail, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.listDate,
            id: this.orderId
          } // props
        },
        area: ['880px', '700px'],
        title: '选择采购送检单明细', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (!this.id) { // 没有id就是新增
          this.formData.id = ''
        }
        if (valid) {
          // 2024/1/23 xjj让加的  原来没有
          if (this.listDate && this.listDate.length <= 0) {
            this.$message.warning('请添加订单明细')
            return
          }
          if (this.listDate.filter(item => !item.inspectNumber).length > 0) {
            this.$message.warning('送检数量不能为空')
            return
          } else if (this.listDate.filter(item => item.inspectNumber && !this.SETTINGS.reg_no_zero.test(item.inspectNumber)).length > 0) {
            this.$message.warning('送检数量未正确填写')
            return
          }
          this.formData.status = '1'
          this.formData.roleIds = this.formData.roleIdsArray
          this.formData.detailList = this.listDate
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 保存
    onSave() {
      this.$refs['form'].validate(valid => {
        if (!this.id) { // 没有id就是新增
          this.formData.id = ''
        }
        if (valid) {
          if (this.listDate && this.listDate.length <= 0) {
            this.$message.warning('请添加订单明细')
            return
          }
          if (this.listDate && this.listDate.filter(item => !item.inspectNumber).length > 0) {
            this.$message.warning('送检数量不能为空')
            return
          } else if (this.listDate.filter(item => item.inspectNumber && !this.SETTINGS.reg_no_zero.test(item.inspectNumber)).length > 0) {
            this.$message.warning('送检数量未正确填写')
            return
          }
          this.formData.status = '0'
          this.formData.roleIds = this.formData.roleIdsArray
          this.formData.detailList = this.listDate
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    showMaterial(data) {
      console.log(data, 22222)
      data.forEach(item => {
        if (!item.purchaseOrderDetailId) {
          item.purchaseOrderDetailId = item.id
          item.id = ''
          delete item.id
        }
      })
      this.listDate = data
    },
    choosePeople() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: purchaseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectionId: this.orderId ? this.orderId : ''
          } // props
        },
        area: ['880px', '700px'],
        title: '选择采购订单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseCustomer(data) {
      this.orderId = data.id
      this.formData.supplierName = data.supplierName
      this.formData.purchaseOrderCode = data.code
      this.formData.purchaseOrderId = data.id
      this.getOrderGetInfo()
    }
  }
}
</script>

<style lang="less" scoped>
.table_container {
  padding-bottom: 20px !important;
}
/deep/ .el-table__fixed-footer-wrapper {
  .el-table__cell:last-of-type {
    height: 39px !important;
  }
}
/**
 * 解决el-input设置类型为number时，中文输入法光标上移问题
 **/
/deep/.el-input__inner{
  line-height: 1px !important;
}

/**
 * 解决el-input设置类型为number时，去掉输入框后面上下箭头
 **/
/deep/ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
